from epwechat.access.token import Token
import requests
import json
from requests_toolbelt import MultipartEncoder
from pathlib import Path


class SendMsg:
    HEADERS = {'Content-Type': 'application/json'}
    fd_headers = {
        'content-type': 'multipart/form-data'
    }

    def __init__(self, corpid: str, corpsecret: str):
        self.appid = 0
        self.corpid = corpid
        self.corpsecret = corpsecret
        self.rds = Token('127.0.0.1', 6379)
        self.token = self.rds.read_cach_token('token')
        if not self.token:
            self.token = Token.get_token(self.corpid, self.corpsecret)
            self.rds.writer_cach_token('token', self.token)
        self.SEND_MSG_BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token
        self.UPLOAD_FILE_BASE_URL = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={self.token}&type=file"

    def send_text(self, touser: int, content: str, msgtype='text', agentid=0):
        """
        :param touser:指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为”@all”，则向该企业应用的全部成员发送
        :param agentid:企业应用的id
        :param content:消息内容，最长不超过2048个字节，超过将截断（支持id转译）
        :param msgtype:消息类型(text:文本消息)
        :return:
        """
        data = {'touser': touser, 'agentid': agentid,
                'text': {'content': content}, 'msgtype': msgtype}
        errcode = requests.post(url=self.SEND_MSG_BASE_URL, data=json.dumps(
            data, ensure_ascii=False).encode('utf-8'), headers=self.HEADERS).json().get('errcode')
        return errcode

    def upload_files(self, file_path: str):
        file_name = Path(file_path).name
        with open(file_path, 'rb') as f:
            content = f.read()

        fields = {
            "media": (file_name, content, '', {})
        }
        m = MultipartEncoder(
            fields=fields
        )
        try:
            resp = requests.post(self.UPLOAD_FILE_BASE_URL, data=m, headers=self.fd_headers).json()
        except Exception as e:
            raise ("上传临时文件异常")
        if resp.get("errcode") != 0:
            raise ("上传临时文件失败")
        return resp

    def upload_file_stream(self, file_stream: bytes, file_name: str):

        fields = {
            "media": (file_name, file_stream, '', {})
        }
        m = MultipartEncoder(
            fields=fields
        )
        try:
            resp = requests.post(self.UPLOAD_FILE_BASE_URL, data=m, headers=self.fd_headers).json()
        except Exception as e:
            raise ("上传临时文件异常")
        if resp.get("errcode") != 0:
            raise ("上传临时文件失败")
        return resp

    def send_file(self, work_code, file_path: str):
        media_id = self.upload_files(file_path).get('media_id')
        if isinstance(work_code, list):
            work_code = "|".join([str(i) for i in work_code])
        data = {
            "touser": work_code,
            "agentid": self.appid,
            "msgtype": "file",
            "file": {
                "media_id": media_id
            },
            "safe": 0
        }

        try:
            resp = requests.post(self.SEND_MSG_BASE_URL, json=data).json()
        except Exception as e:
            raise ("发送异常")
        if resp.get("errcode") != 0:
            raise ("发送失败")

        return resp

    def send_file_stream(self, work_code, file_stream: bytes, file_name: str):
        media_id = self.upload_file_stream(file_stream, file_name).get('media_id')
        if isinstance(work_code, list):
            work_code = "|".join([str(i) for i in work_code])
        data = {
            "touser": work_code,
            "agentid": self.appid,
            "msgtype": "file",
            "file": {
                "media_id": media_id
            },
            "safe": 0
        }

        try:
            resp = requests.post(self.SEND_MSG_BASE_URL, json=data).json()
        except Exception as e:
            raise ("发送异常")
        if resp.get("errcode") != 0:
            raise ("发送失败")
        return resp
